package com.toutiao

import java.io.File
import com.typesafe.config._

import org.apache.log4j.Logger
import org.apache.log4j.PropertyConfigurator

import com.toutiao.issue.Data
import com.toutiao.issue.SimpleModel
import com.toutiao.score.Measure
import com.toutiao.score.Scorer

import com.toutiao.issue.SimTitleProcess // 内存
import com.toutiao.nssue.NssTitleProcess // LevelDB
import com.toutiao.vssue.VssTitleProcess // LevelDB + Kafka + Model


// 内存版本+内存Cache/LevelDB版本

class AppProp(
  val data: Map[String, String]) {
  def apply(key: String) = data(key)
}

object MainApp extends App {

  val cc = Array(
    "MODE",
    
    "LOCATION_DOCUMENT",
    "LOCATION_TOPIC",
    
    "LOCATION_MEASURE",
    "DOC_NUM",
    "MIN_V",
    "MIN_S",
    
    "ES_DOC_NAME",
    "ES_DOC_URI",
    "ES_DOC_PORT",
    "ES_DOC_INDEX",
    "ES_DOC_TYPE",
    
    "ES_TOPIC_NAME",
    "ES_TOPIC_URI",
    "ES_TOPIC_PORT",
    "ES_TOPIC_INDEX",
    "ES_TOPIC_TYPE",
    
    "LOCATION_DATE",
    "TIME_SIZE",
    "TIME_STEP",
    
    "DB_LOCATION",
    "DB_CACHE",
    "DB_ROOT",
    
    "ZOOKEEPER",
    "CRAWL_TOPIC1",
    "CRAWL_TOPIC2",
    "CRAWL_TOPIC1_ACK",
    "CRAWL_TOPIC2_ACK",
    "GROUP_ID",
    
    "SIM_TOPIC1",
    "SIM_TOPIC2",
    "BROKERS",
    
    "DOCID_NAME",
    "SIMID_NAME",    
    
    "ID_URI"
  )

  println("Hello")
  
  var location_log4j = "log4j.properties"
  var location_sim = "SimTitle.properties"
  
  if (args.size == 2) {
    location_log4j = args(0)
    location_sim = args(1)
  }

  PropertyConfigurator.configure(location_log4j)
  val _log = Logger.getLogger(this.getClass.getName)

  val c = ConfigFactory.parseFile(new File(location_sim))

  def initAppProp = {
    val m = cc.map(v => {
      (v, c.getString(v))
    }).toMap
    new AppProp(m)
  }

  val prop = initAppProp

  val m = c.getInt("MODE")

  // 线下测试
  if (m == 0) {
    val locationDoc = prop("LOCATION_DOCUMENT")
    val locationTopic = prop("LOCATION_TOPIC")
    val locationMeasure = prop("LOCATION_MEASURE")

    val minV = prop("MIN_V").toDouble
    val minS = prop("MIN_S").toDouble

    _log.info(locationDoc + " " + locationTopic + " " + locationMeasure)
    _log.info(minV + " " + minS)

    val p = new SimpleModel(minV, minS)
    
    val m = Measure.get(locationMeasure)
    val n = prop("DOC_NUM").toInt
    val scorer = new Scorer(m,n)

    val xs = Data.getRawDocument(locationDoc)
    val data = Data.convertDocument(scorer, xs)
    _log.info(data.size)
    p.run(data)
    _log.info("Sim Done")
    p.save(locationTopic)
    _log.info("Save Done")
  }
  
  // 第一代, 内存, ES输入输出
  if (m == 1){
    SimTitleProcess.run(prop)
  }
  
  // 第二代, LevelDB, ES输入输出
  if (m == 2){
    NssTitleProcess.run(prop)
  }
  
  // 第三代, LevelDB, Kafka输入输出
  if (m == 3) {
    VssTitleProcess.run(prop)
  }

}
